#!/bin/bash

if [[ ${BACKUP_DAYS} == "" ]]; then
	echo "Missing BACKUP_DAYS env variable"
	exit 1
fi

if [[ ${DB_USER} == "" ]]; then
	echo "Missing DB_USER env variable"
	exit 1
fi

if [[ ${DB_PASSWORD} == "" ]]; then
	echo "Missing DB_PASSWORD env variable"
	exit 1
fi

if [[ ${DB_NAMES} == "" ]]; then
	echo "Missing DB_NAME env variable"
	exit 1
fi

if [[ ${DB_HOST} == "" ]]; then
	echo "Missing DB_HOST env variable"
	exit 1
fi

if [[ ${DB_PORT} == "" ]]; then
	echo "Missing DB_PORT env variable"
	exit 1
fi

BACKUP_DIR=/var/db/backup
TIMESTAMP=`date +%Y%m%d`

databases=(`echo $DB_NAMES | tr ',' ' '`) 

echo ${databases[@]}
echo ${#databases[@]}

if [[ ${#databases[@]} -lt 2 ]]; then
    #获取数据库名称
	databases=`mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWORD} -Ne "show databases"`;
fi
echo "Dumping database: ${databases[@]}" >> ${BACKUP_DIR}/log.txt
for item in ${databases[@]}; 
do
    echo "Dumping database: ${item}"
	if [ $item != "" -a $item != "mysql" -a $item != "test" -a $item != "mydata" -a $item != "information_schema" -a $item != "performance_schema" ]; then
		mysqldump -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWORD} --triggers --routines --events $item | gzip -3 > ${BACKUP_DIR}/${item}_${TIMESTAMP}.gz
		#echo $item >> ${BACKUP_DIR}/log.txt
		#写创建备份日志
		echo "create ${BACKUP_DIR}/${item}-${TIMESTAMP}.gz" >> ${BACKUP_DIR}/log.txt
	fi
	 
done

# 删除过期备份
echo "================delete ${BACKUP_DAYS} days algo file ================" >> ${BACKUP_DIR}/log.txt
find ${BACKUP_DIR}/ -type f  -name "*.gz" -mtime +${BACKUP_DAYS} -exec rm -f {} \;
 
